package org.duiduo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.duiduo.api.constant.ResponseConsts;
import org.duiduo.api.request.RoleRequest;
import org.duiduo.api.response.RespBean;
import org.duiduo.config.security.compoment.JwtTokenUtil;
import org.duiduo.exception.BizException;
import org.duiduo.mapper.RoleMapper;
import org.duiduo.pojo.Role;
import org.duiduo.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liangze
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private RoleMapper mapper;

    @Override
    public Role getRoleByUsername(String username) {
        return mapper.selectOne(new QueryWrapper<Role>()
                .eq("username", username));
    }

    @Override
    public RespBean addRole(RoleRequest request) {
        Role role = new Role();
        BeanUtil.copyProperties(request, role, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        // 密码加密
        role.setPassword(passwordEncoder.encode(role.getPassword()));
        mapper.insert(role);
        return RespBean.success(ResponseConsts.RespSuccessMsg.RESP_MSG_INSERT.getMessage());
    }

    @Override
    public RespBean login(String username, String password, HttpServletRequest request) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (null == userDetails || !passwordEncoder.matches(password, userDetails.getPassword())) {
            throw new BizException(ResponseConsts.RespErrorMsg.RESP_MSG_3.getMessage());
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String, String> tokenMap = new HashMap<>(16);
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return RespBean.success(ResponseConsts.RespSuccessMsg.RESP_MSG_1.getMessage(), tokenMap);
    }
}
